package com.acme.bankapp.domain.client;

import com.acme.bankapp.domain.account.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Client implements Serializable {
    private Gender gender;
    private String name;
    private List<Account> accounts = new ArrayList<Account>();

    public List<Account> getAccounts() {
        return Collections.unmodifiableList(accounts);
    }

    public Client(final String name, final Gender gender) {
        this.name = name;
        this.gender = gender;
    }

    public String getClientSalutation() {
        return gender.toString() + " " + name;
    }

    public String getName() {
        return name;
    }

    public void addAccount(final Account account) {
        if (getAccountById(account.getId()) != null) {
            System.out.println("Account with id=" + account.getId() + " has already been added earlier");
        }
        accounts.add(account);
    }

    public Account getAccount(final int id) {
        for (Account account : accounts) {
            if (account.getId() == id) {
                return account;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        StringBuffer ClientWithAccountsString = new StringBuffer("Client " + getClientSalutation() + "\n  accounts:\n");
        for (Account account : accounts) {
            ClientWithAccountsString.append("    ");
            ClientWithAccountsString.append(account);
            ClientWithAccountsString.append("\n");
        }
        return ClientWithAccountsString.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Client client = (Client) o;

        // Comparison of business keys (name, may be gender) is enough
        // if (accounts != null ? !accounts.equals(client.accounts) : client.accounts != null) return false;
        if (gender != client.gender) return false;
        if (name != null ? !name.equals(client.name) : client.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = gender != null ? gender.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (accounts != null ? accounts.hashCode() : 0);
        return result;
    }

    public Account getAccountById(final int id) {
        for (Account account : accounts) {
            if (account.getId() == id) {
                return account;
            }
        }
        return null;
    }
}
